<template>
  <van-popup
    :show="modelValue"
    position="left"
    :style="{ width: '80%', height: '100%', backgroundColor: '#f7f8fa' }"
    @update:show="$emit('update:modelValue', $event)"
  >
    <div class="history-header">
      <van-image round width="4.5rem" height="4.5rem" :src="aiAvatar" />
      <span>AI小诺</span>
    </div>
    
    <div class="sidebar">
      <van-button 
        type="primary" 
        block 
        round 
        icon="plus" 
        @click="handleNewChat"
        class="new-chat-btn"
      >
        新对话
      </van-button>

      <div class="chat-history">
        <div class="section-title">历史对话</div>
        <van-cell-group inset>
          <van-swipe-cell 
            v-for="chat in historyList" 
            :key="chat.id"
            :name="chat.id"
            @open="handleSwipeOpen"
            @close="handleSwipeClose"
            :before-close="beforeClose"
          >
            <van-cell 
              :title="chat.title"
              :label="formatDate(chat.updateTime)"
              @click="handleChatSelect(chat)"
              class="history-item"
            >
              <template #icon>
                <van-icon name="chat-o" class="chat-icon" />
              </template>
              
              <!-- 右侧滑动提示 -->
              <template #right-icon>
                <div class="swipe-hint" v-show="!activeSwipeId || activeSwipeId !== chat.chatId">
                  <span class="hint-text">向左滑动</span>
                  <van-icon name="arrow" class="arrow-icon" />
                </div>
              </template>
            </van-cell>
            
            <!-- 滑动操作按钮 -->
            <template #right>
              <van-button 
                square 
                type="primary" 
                text="编辑" 
                class="edit-button"
                @click.stop="handleEditChat(chat)"
              />
              <van-button 
                square 
                type="danger" 
                text="删除" 
                class="delete-button"
                @click.stop="handleDeleteChat(chat.chatId)"
              />
            </template>
          </van-swipe-cell>
        </van-cell-group>
      </div>

      <!-- 编辑对话框 -->
      <van-dialog
        v-model:show="showEditDialog"
        title="编辑对话"
        show-cancel-button
        @confirm="confirmEdit"
        @cancel="cancelEdit"
      >
        <van-field
          v-model="editingChat.title"
          label="对话标题"
          placeholder="请输入新标题"
          :rules="[{ required: true, message: '请输入标题' }]"
          maxlength="20"
          show-word-limit
        />
      </van-dialog>

      <div class="user-info">
        <van-image round width="40px" height="40px" :src="avatar" class="user-avatar" />
        <div class="user-meta">
          <div class="user-name">{{ username }}</div>
          <div class="user-desc">{{ userDesc }}</div>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script>
export default {
  name: 'ChatSidebar'
}
</script>

<script setup>
import { ref } from 'vue';
import { showConfirmDialog, showToast } from 'vant';
import Avatar from '@/assets/img/robot.png';

const aiAvatar = Avatar;

// 状态管理
const showEditDialog = ref(false);
const editingChat = ref({ id: null, title: '' });
const activeSwipeId = ref(null); // 当前激活的滑动项ID

const props = defineProps({
  modelValue: Boolean,
  historyList: {
    type: Array,
    default: () => []
  },
  avatar: {
    type: String,
    default: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  },
  username: {
    type: String,
    default: '用户名'
  },
  userDesc: {
    type: String,
    default: 'VIP会员'
  }
});

const emit = defineEmits([
  'update:modelValue',
  'new-chat',
  'select-chat',
  'edit-chat',
  'delete-chat'
]);

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '无日期';
  
  // 确保传入的是合法的 Date 对象
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return '无效日期'; // 检查是否 Invalid Date
  
  // 只返回年月日（如 "2023年6月1日"）
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// 新建对话
const handleNewChat = () => {
  emit('update:modelValue', false);
  emit('new-chat');
};

// 选择对话
const handleChatSelect = (chat) => {
  // 如果有滑动项打开，先关闭
  if (activeSwipeId.value) {
    return;
  }
  emit('update:modelValue', false);
  emit('select-chat', chat);
};

// 编辑对话
const handleEditChat = (chat) => {
  editingChat.value = { ...chat };
  showEditDialog.value = true;
  activeSwipeId.value = null; // 重置滑动状态
};

// 删除对话
const handleDeleteChat = (chatId) => {
  showConfirmDialog({
    title: '确认删除',
    message: '删除后对话将不可恢复，确定删除吗？',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonColor: 'var(--van-danger-color)'
  }).then(() => {
    emit('delete-chat', chatId);
    // showToast('删除成功');
  }).catch(() => {
    // 取消删除
  });
};

// 确认编辑
const confirmEdit = () => {
  if (editingChat.value.title.trim()) {
    emit('edit-chat', editingChat.value);
    showToast('修改成功');
    editingChat.value = { id: null, title: '' };
  }
};

// 取消编辑
const cancelEdit = () => {
  editingChat.value = { id: null, title: '' };
};

// 滑动打开时记录当前项
const handleSwipeOpen = ({ name }) => {
  activeSwipeId.value = name;
};

// 滑动关闭时重置状态
const handleSwipeClose = () => {
  activeSwipeId.value = null;
};

// 滑动前处理
const beforeClose = ({ position }) => {
  // 只允许从右侧滑动关闭
  return position !== 'right';
};
</script>

<style scoped>
.history-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  text-align: center;
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
}

.history-header span {
  font-size: 18px;
  font-weight: 500;
  margin-top: 10px;
}

.sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
}

.new-chat-btn {
  width: 70%;
  margin: 15px auto;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px;
}

.section-title {
  padding: 12px 16px;
  color: #969799;
  font-size: 14px;
}

.history-item {
  cursor: pointer;
  transition: all 0.2s;
  padding-right: 30px; /* 为提示留出空间 */
}

.history-item:active {
  background-color: #f5f5f5;
}

.chat-icon {
  margin-right: 8px;
  color: var(--van-blue);
}

.user-info {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: white;
  border-top: 1px solid #f0f0f0;
}

.user-avatar {
  flex-shrink: 0;
}

.user-meta {
  margin-left: 12px;
  overflow: hidden;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-desc {
  font-size: 12px;
  color: #969799;
  margin-top: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 滑动提示样式 */
.swipe-hint {
  display: flex;
  align-items: center;
  color: #c8c9cc;
  padding-right: 8px;
  transition: all 0.3s;
}

.hint-text {
  font-size: 12px;
  margin-right: 4px;
}

.arrow-icon {
  font-size: 14px;
  transform: rotate(180deg);
  animation: hintPulse 2s infinite;
}

@keyframes hintPulse {
  0% { opacity: 0.6; transform: rotate(180deg) translateX(0); }
  50% { opacity: 1; transform: rotate(180deg) translateX(-3px); }
  100% { opacity: 0.6; transform: rotate(180deg) translateX(0); }
}

/* 操作按钮样式 */
.edit-button {
  height: 100%;
  background-color: var(--van-blue);
  border-radius: 0;
}

.delete-button {
  height: 100%;
  border-radius: 0;
}

/* 滑动单元格样式 */
:deep(.van-swipe-cell) {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 8px;
}

:deep(.van-swipe-cell__wrapper) {
  border-radius: 8px;
  transition: transform 0.3s;
}

/* 对话框样式 */
:deep(.van-dialog__header) {
  font-size: 18px;
  font-weight: 500;
  padding: 16px;
}

:deep(.van-dialog__content) {
  padding: 16px;
}

:deep(.van-field__label) {
  width: 80px;
}

/* 历史记录项样式 */
:deep(.van-cell__title) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 适配暗黑模式 */
@media (prefers-color-scheme: dark) {
  .sidebar {
    background-color: #1a1a1a;
  }
  
  .history-header,
  .user-info {
    background-color: #2a2a2a;
    border-color: #333;
  }
  
  .swipe-hint {
    color: #666;
  }
}
</style>